const api = require('../../utils/api.js');
const tools = require('../../utils/getuserinfo.js');
const utils = require('../../utils/utils.js');
const app = getApp();

Page({
  data: {
    avatar: '',
    company: '',
    payment: -1,
    inputmoney: 0,
    money: -1,
    content: '',
    show_payment: false,
    pay_type_list: [],
    theme: app.themeData,
    unit: '',
    showcoupon: false,
    couponlist: [],
    checkItem: '',
    reload: false,
    key: true,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    payFrozen: false,
    imgUrl: app.imgUrl,
    isLoad: false,
  },

  onLoad(options) {
    let that = this;
    let userinfo = wx.getStorageSync('user_info');
    let scene = decodeURIComponent(options.scene);
    let cashierId = null;
    if (scene && scene !== 'undefined') {
      scene = utils.scene_decode(scene);
      app.ws_micro_shop_globalData.shopid = scene.sid;
      cashierId = scene.cashier_id ? scene.cashier_id : '';
      userinfo = false;
    }
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
        cashierId,
      });
    });
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      this.loadPayList();
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 &&
          tools.onGetInfo(that, userinfo.auth_mode);
        that.loadPayList();
      });
    }
  },

  bindMember(parent_id) {
    app.ws_micro_shoprequest({
      url: api.share.bind_parent,
      data: {
        parent_id,
      },
      success: res => {
        if (res.code === 0) {
          if (res.data && res.data.access_token) {
            wx.setStorageSync('access_token', res.data.access_token);
          }
        }
      },
    });
  },

  loadPayList() {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.facepay,
      method: 'GET',
      success: function(res) {
        if (res.code === 0) {
          wx.hideLoading();
          let { picture, name, pay_type_list, level_discount } = res.data;
          that.setData(
            {
              avatar: picture,
              company: name,
              pay_type_list,
              level_discount,
              isLoad: true,
            },
            () => {
              if (that.data.cashierId) {
                that.bindMember(that.data.cashierId);
              }
            }
          );
        } else {
          app.util.navigateTo('/ws_micro_shop/pages/index/index');
        }
      },
    });
  },

  getMoney(e) {  // cd
    let money = Number(e.detail.value);
    let { inputmoney } = this.data;
    if (money !== Number(inputmoney)) {
      this.setData({
        reload: true,
        // checkItem: '',
      }, () => {
        this.loadCouponList();
      });
    } else {
      this.setData({
        reload: false,
      });
    }
    this.setData({
      money: money.toFixed(2),
      inputmoney: money,
      key: true,
    });
    // this.calcPayTotal();
  },

  getContent(e) {
    this.setData({
      content: e.detail.value.trim(),
    });
  },

  showPayment() {
    this.setData({
      show_payment: true,
    });
  },

  payPicker(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      payment: index,
    });
  },

  disableClick() {
    // it`s necessary
  },

  payClose() {
    let that = this;
    let paytype = that.data.payment;
    if (Number(paytype) === 3) {
      wx.showModal({
        title: '友情提示',
        content: '是否确定选择账户余额支付',
        success: function(res) {
          if (res.confirm) {
            that.setData({
              show_payment: false,
            });
          }
        },
      });
    } else if (Number(paytype) === 5) {
      let card = that.data.card;
      if (card) {
        that.setData({
          show_payment: false,
        });
      } else {
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function(res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    } else {
      that.setData({
        show_payment: false,
      });
    }
  },

  calcPayTotal() {
    let { checkItem, inputmoney, level_discount } = this.data;
    let money = 0;
    money = Number(level_discount ? ((inputmoney * level_discount) / 10).toFixed(2) : inputmoney);
    if (checkItem && checkItem.checked) {
      money = money - checkItem.sub_price;
      money = money > 0 ? money.toFixed(2) : 0.01;
    } else {
      money = money.toFixed(2);
    }

    this.setData({
      money,
    });
  },

  payNow() {
    let that = this;
    let coupon_id = '';
    let { money, payment, content, checkItem } = this.data;
    if (!money) {
      wx.showToast({
        title: '支付金额不能为空',
        icon: 'none',
      });
      return;
    }
    if (money <= 0) {
      wx.showToast({
        title: '支付金额不能小于0',
        icon: 'none',
      });
      return;
    }
    if (payment < 0) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
      return;
    }
    that.setData({
      payFrozen: true,
    });
    checkItem && (coupon_id = checkItem.user_coupon_id);
    let cashierId = that.data.cashierId;
    let payData = {
      money,
      content,
      coupon_id,
      url: that.getUrl(),
    };
    if (cashierId && Boolean(cashierId)) {
      payData.cashier_id = cashierId;
    }
    if (payment === 0) {
      payData.pay_type = 'WECHAT_PAY';
      app.ws_micro_shoprequest({
        url: api.default.paymoney,
        method: 'POST',
        data: payData,
        success: function(res) {
          if (res.code === 0) {
            let { timeStamp, nonceStr, signType, paySign } = res.data;
            wx.requestPayment({
              timeStamp,
              nonceStr,
              package: res.data.package,
              signType,
              paySign,
              complete: function(e) {
                if (
                  e.errMsg === 'requestPayment:fail' ||
                  e.errMsg === 'requestPayment:fail cancel'
                ) {
                  wx.showModal({
                    title: '提示',
                    content: '支付失败',
                    showCancel: false,
                    confirmText: '确认',
                    success: function(res) {
                      if (res.confirm) {
                        app.util.navigateTo('/ws_micro_shop/pages/index/index');
                      }
                    },
                  });
                  return;
                }
                if (e.errMsg === 'requestPayment:ok') {
                  if (res.data.send_integeral > 0) {
                    wx.showToast({
                      title: '支付成功,赠送' + res.data.send_integeral + '积分',
                      icon: 'none',
                    });
                  } else {
                    wx.showToast({
                      title: '支付成功',
                    });
                  }
                  setTimeout(function() {
                    app.util.navigateTo('/ws_micro_shop/pages/index/index');
                  }, 1000);
                  return;
                }
              },
            });
            return;
          }
          if (res.code === 1) {
            wx.showToast({
              title: res.msg || '支付失败',
              icon: 'none',
            });
            setTimeout(function() {
              app.util.navigateTo('/ws_micro_shop/pages/index/index');
            }, 1000);
            return;
          }
        },
      });
    }
    if (payment === 3) {
      payData.pay_type = 'BALANCE_PAY';
      app.ws_micro_shoprequest({
        url: api.default.paymoney,
        method: 'POST',
        data: payData,
        success: function(res) {
          if (res.code === 0) {
            if (res.data.send_integeral > 0) {
              wx.showToast({
                title: '支付成功,赠送' + res.data.send_integeral + '积分',
                icon: 'none',
              });
            } else {
              wx.showToast({
                title: '支付成功',
              });
            }
            setTimeout(function() {
              app.util.navigateTo('/ws_micro_shop/pages/index/index');
            }, 1000);
            return;
          } else {
            wx.showToast({
              title: res.msg || '支付失败',
              icon: 'none',
            });
            // setTimeout(function () {
            //   app.util.navigateTo('/ws_micro_shop/pages/index/index');
            // }, 1000);
            return;
          }
        },
      });
    }
    if (payment === 5) {
      payData.pay_type = 'CARD_PAY';
      app.ws_micro_shoprequest({
        url: api.default.paymoney,
        method: 'POST',
        data: payData,
        success: function(res) {
          if (res.code === 0) {
            if (res.data.send_integeral > 0) {
              wx.showToast({
                title: '支付成功,赠送' + res.data.send_integeral + '积分',
                icon: 'none',
              });
            } else {
              wx.showToast({
                title: '支付成功',
              });
            }
            setTimeout(function() {
              app.util.navigateTo('/ws_micro_shop/pages/index/index');
            }, 1000);
          } else {
            wx.showToast({
              title: res.msg || '支付失败',
              icon: 'none',
            });
          }
        },
      });
    }
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  showCouponModel() {
    let { reload, key } = this.data;
    if (!(reload && key)) {
      this.setData({
        showcoupon: true,
      })
    }
    // this.loadCouponList();
  },

  hideCouponModel() {
    // let list = this.data.couponlist;
    // let k = 0;
    // for (let i in list) {
    //   if (!list[i].checked) {
    //     k += 1;
    //   }
    // }
    // if (k === list.length) {
    //   this.setData({
    //     checkItem: '',
    //   });
    // }
    let { checkItem, couponlist } = this.data;
    couponlist.forEach((item)=> {
      if (item.checked) item.checked = false;
    })
    if (checkItem) {
      let index = couponlist.findIndex(item => Number(item.user_coupon_id) === Number(checkItem.user_coupon_id));
      couponlist[index].checked = true;
    }
    this.setData({
      showcoupon: false,
      couponlist,
    });
    // this.calcPayTotal();
  },

  selectCouponItem() {
    let list = this.data.couponlist;
    let k = 0;
    let checkItem = '';
    for (let i in list) {
      if (list[i].checked) {
        checkItem = list[i];
        break;
      } else {
        k += 1;
      }
    }
    this.setData({
      showcoupon: false,
      checkItem: k === list.length ? '' : checkItem,
    })
    // if (k === list.length) {
    //   wx.showToast({
    //     title: '请选择要使用的优惠券',
    //     icon: 'none',
    //   });
    // } else {
      this.calcPayTotal();
    // }
  },

  pickCoupon(e) {
    let { id } = e.currentTarget.dataset;
    let list = this.data.couponlist;
    for (let i in list) {
      if (Number(id) === Number(list[i].user_coupon_id)) {
        list[i].checked = !list[i].checked;
      } else {
        list[i].checked = false;
      }
    }
    this.setData({
      couponlist: list,
    });
  },

  loadCouponList() {
    let that = this;
    let { reload, key, inputmoney, checkItem } = that.data;
    if (reload && key) {
      app.ws_micro_shoprequest({
        url: api.default.faceuse,
        data: {
          money: inputmoney,
        },
        success: function(res) {
          if (res.code === 0) {
            // 判断一下当前选择的优惠券是否在返回的接口中 再决定是否情况优惠券  cd 20200114
            let couponlist = res.data;
            if (checkItem) {
              let index = couponlist.findIndex(item => Number(item.user_coupon_id) === Number(checkItem.user_coupon_id));
              if (index === -1) {
                that.setData({
                  checkItem: '',
                });
                
              } else {
                // 将返回的优惠券 加上选中标识 checked
                couponlist[index].checked = true;
              }

            }
            that.setData({
              couponlist,
              key: false,
              // showcoupon: true,
            }, () => {
              that.calcPayTotal();
            });

          } else {
            wx.showToast({
              title: res.msg || '暂无可用优惠券',
              icon: 'none',
            });
          }
        },
      });
    }
  },

  getUrl() {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    let url = currentPage.route;
    let options = currentPage.options;
    let urlWithArgs = `/${url}?`;
    for (let key in options) {
      if (options.hasOwnProperty(key)) {
        let value = decodeURIComponent(options[key]);
        urlWithArgs += `${key}=${value}&`;
      }
    }

    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
    return urlWithArgs;
  },
});
